use inquire::{self, required, ui::RenderConfig, validator::Validation, Confirm, Text};

#[derive(Debug)]
pub struct MailAddressData {
    /// 邮箱地址
    pub address: String,
    /// 发送人名称
    pub sender_name: String,
    /// 授权码
    pub credential_code: String,
    /// 邮箱对应的smtp服务地址
    pub mail_server_address: String,
}
///要询问的问题：邮箱地址，邮箱密码
pub fn ask_info() -> MailAddressData {
    // let options=vec!["qq邮箱","163邮箱","钉钉邮箱(未实现)"];
    // let mail_type=Select::new("请选择邮箱类型",options).prompt().unwrap();
    let mail_address = Text::new("请输入邮箱地址")
        .with_validator(|address: &str| {
            if &address.len() < &1 {
                return Ok(Validation::Invalid("请输入邮箱地址".into()));
            }
            if address.ends_with("@qq.com") || address.ends_with("@163.com") {
                return Ok(Validation::Valid);
            }
            return Ok(Validation::Invalid(
                "请重新输入邮箱地址，目前仅支持qq邮箱和163邮箱".into(),
            ));
        })
        .prompt()
        .unwrap();
    #[allow(unused_assignments)]
    let mut mail_server_address = "".to_owned();
    if mail_address.ends_with("@qq.com") {
        mail_server_address = "smtp.qq.com".to_owned()
    } else {
        mail_server_address = "smtp.163.com".to_owned()
    }
    let mail_credential = Text::new("请输入邮箱授权码")
        .with_validator(required!("请输入邮箱授权码"))
        .prompt()
        .unwrap();
    let mail_sender = Text::new("请输入发送人名称")
        .with_validator(required!("请输入发送人名称"))
        .prompt()
        .unwrap();
    let sure = Confirm {
        message: &format!(
            "请检查输入的数据\r\n邮箱地址：{}\r\n发件人：{}\r\n授权码：{}\r\n",
            mail_address, mail_sender, mail_credential
        ),
        default: None,
        placeholder: None,
        help_message: Some("如果一切正常，请回车。如有问题，请输入 no "),
        formatter: &|ans| match ans {
            true => "".to_owned(),
            false => "no".to_owned(),
        },
        parser: &|ans| match ans {
            "" => Ok(true),
            "no" => Ok(false),
            _ => Ok(true),
        },
        default_value_formatter: &|def| match def {
            true => String::from(""),
            false => String::from("no"),
        },
        error_message: "输入的数据有问题吗？如果有问题要重写，请输入no；如果没问题，请按下回车"
            .to_owned(),
        render_config: RenderConfig::default(),
    }
    .prompt()
    .unwrap();
    if sure {
        return MailAddressData {
            address: mail_address,
            sender_name: mail_sender,
            credential_code: mail_credential,
            mail_server_address,
        };
    } else {
        return ask_info();
    }
}
